﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using Model;

namespace Dal
{
    public class BaseDal<T> where T:class,new()
    {
        public DbContext CurrentDbContext {
            get { return DbContextUtil.GetCurrentDbContext(); }
        }

        #region 增加
        public T Add(T entity)
        {
            CurrentDbContext.Set<T>().Add(entity);
            //dbContext.SaveChanges();
            return entity;//因为EF在添加一个实体后，会将实体的id（自增长）赋值，再返回实体
        }
        #endregion

        #region 删除
        public bool Delete(T entity)
        {
            CurrentDbContext.Entry(entity).State = EntityState.Deleted;
            //return dbContext.SaveChanges()>0;
            return true;
        }
        #endregion

        #region 修改
        public bool Update(T entity)
        {
            CurrentDbContext.Entry(entity).State = EntityState.Modified;
            //return dbContext.SaveChanges() > 0;
            return true;
        }
        #endregion

        #region 一般查询
        /// <summary>
        /// 
        /// </summary>
        /// <param name="whereLambda"></param>
        /// <returns></returns>
        public IQueryable<T> GetEntities(Expression<Func<T, bool>> whereLambda)
        {
            return CurrentDbContext.Set<T>().Where(whereLambda);
        }
        #endregion

        #region 分页查询
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="S">排序的属性的类型</typeparam>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <param name="total">总数据数（符合条件的）</param>
        /// <param name="whereLambda"></param>
        /// <param name="orderbyLambda"></param>
        /// <param name="isAsc"></param>
        /// <returns></returns>
        public IQueryable<T> GetEntitiesByPage<S>(int pageSize, int pageIndex, out int total, Expression<Func<T, bool>> whereLambda, Expression<Func<T, S>> orderbyLambda, bool isAsc)
        {
            total = CurrentDbContext.Set<T>().Where(whereLambda).Count();
            if (isAsc)
            {
                var temp = CurrentDbContext.Set<T>().Where(whereLambda)
                    .OrderBy(orderbyLambda)
                    .Skip(pageSize * (pageIndex - 1))
                    .Take(pageSize).AsQueryable();
                return temp;
            }
            else
            {
                var temp = CurrentDbContext.Set<T>().Where(whereLambda)
                    .OrderByDescending(orderbyLambda)
                    .Skip(pageSize * (pageIndex - 1))
                    .Take(pageSize).AsQueryable();
                return temp;
            }

        }
        #endregion
    }
}
